# -*- coding: utf-8 -*-
"""

    taggable.managers
    -----------------

    Managers.

    :copyright: 2008 by Gustavo Picon
    :license: Apache License 2.0

"""

from django.db import models, transaction, connection


class TaggedQuerySet(models.query.QuerySet):
    """ Queryset for the Tagged abstract class.
    """


    def delete(self):
        """ Removes a set of tagged objects and updates the stats tables.
        """
        cursor = connection.cursor()

        for tagged in self:

            for fields, relmodel in tagged.__class__.taggable_stats:
                table = relmodel._meta.db_table
                cols, vals = tagged._get_fields(relmodel, fields)
                colstr = ' AND '.join(['%s=%%s' % col for col in cols])
                sql = 'UPDATE %s SET count=count-1 WHERE %s' % (table, colstr)
                cursor.execute(sql, vals)

        super(TaggedQuerySet, self).delete()
        transaction.commit_unless_managed()


class TaggedManager(models.Manager):
    """ Manager for the Tagged abstract class.
    """

    def get_query_set(self):
        """
        """
        return TaggedQuerySet(self.model)
